package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.HeiNiuBaoService;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.MD5Util;
import com.meirengu.webview.model.KwThirdback;
import com.meirengu.webview.service.KwThirdbackService;
import com.meirengu.webview.utils.ConfigUtil;
import com.meirengu.webview.utils.DES;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 黑牛相关服务提供
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class HeiNiuBaoServiceImpl implements HeiNiuBaoService {

    Logger logger = LoggerFactory.getLogger(HeiNiuBaoServiceImpl.class);
    @Autowired
    KwThirdbackService kwThirdbackService;

    /**
     * @param sex   性别 M(男)或F(女)
     * @param name  用户姓名
     * @param phone 电话
     * @param birth 出生日期
     */
    @Override
    public void enhanced(String name, String sex, String phone, String birth) {

        StringBuffer url = new StringBuffer(ConfigUtil.getConfig("heiniubao.url"));
        String channel = ConfigUtil.getConfig("heiniubao.channel");
        String subchannel = ConfigUtil.getConfig("heiniubao.subchannel");
        String key = ConfigUtil.getConfig("heiniubao.key");
        Map<String, String> params = new HashMap<>();
        //如果传的是1和2，转一下
        if ("1".equals(sex)) {
            sex = "M";
        } else if ("2".equals(sex)) {
            sex = "F";
        }
        url.append("?sex=").append(paramFormat(sex, key))
                .append("&name=").append(paramFormat(name, key))
                .append("&phone=").append(paramFormat(phone, key))
                .append("&channel=").append(channel)
                .append("&subchannel=").append(subchannel)
                .append("&birth=").append(paramFormat(birth, key))
                .append("&sign=").append(MD5Util.get32MD5(name + phone + channel + "baoxian-$@"));
        KwThirdback thirdback = new KwThirdback();
        thirdback.setInterfaceCode("heiniu");
        thirdback.setInterfaceName("黑牛保险");
        thirdback.setMobile(phone);
        thirdback.setSendUrl(url.toString());
        thirdback.setParams(params.toString());
        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doGet(url.toString());
            thirdback.setBackUrl(hr.toString());
            thirdback.setHttpCode(hr.getStatusCode());
            thirdback.setHttpContent(hr.getContent());
            int code = hr.getStatusCode();
            if (code == 200) {
                logger.info("==HeiNiuBaoServiceImpl.enhanced request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String status = returnMsg.getString("error_code");
                thirdback.setMessage(returnMsg.getString("error_code") + "---" + returnMsg.getString("error_msg"));
                if ("0".equals(status)) {
                    logger.info("==HeiNiuBaoServiceImpl.enhanced enhanced success");
                } else {
                    logger.warn("==HeiNiuBaoServiceImpl.enhanced enhanced fail");
                }
            } else {
                logger.warn("==HeiNiuBaoServiceImpl.enhanced request fail. code:{}, result:{}", code, hr.toString());
            }
            kwThirdbackService.insert(thirdback);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    private String paramFormat(String param, String key) {
        byte[] b = param.getBytes();
        byte[] a = DES.encrypt(b, key);
        byte[] s = Base64.encodeBase64(a);
        System.out.println(new String(s));
        String result = "";
        try {
            result = URLEncoder.encode(new String(s), "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return result;
    }

    public static void main(String[] args) {
        HeiNiuBaoServiceImpl p = new HeiNiuBaoServiceImpl();
        //p.paramFormat("18813099929","6ec497c7");
        p.enhanced("李思敏", "2", "18813099929", "1989-10-19");
    }
}
